<template>
    <div class="agora-container" ref="container">
        <!-- 远程视频容器 -->
        <video id="zzzaaa" src="http://live-stock.live/video/video1.mp4"></video>
        <div class="mmmbbb" @click="zzc">
            qqqq前期去去去
        </div>
        <!-- <div id="remote-container" ref="remoteContainer"></div> -->

        <!-- 视频控制栏（始终显示） -->
        <!-- <div class="controls-bar" ref="chajian">
            <button @click="toggleFullscreen" class="control-btn" title="Full screen">
                {{ isFullscreen ? '⛶ &nbsp; zo' : '⛶ &nbsp; zi' }}
            </button>
            <button v-if="yl" @click="toggleMute" class="control-btn" title="mute">
                {{ isMuted ? '🔇 Unmute' : '🔊 mute' }}
            </button>
            <input v-if="yl" type="range" min="0" max="100" v-model="volume" class="volume-slider"
                title="Volume adjustment">
            <span v-if="yl" class="volume-text">{{ volume }}%</span>
        </div> -->
    </div>
</template>
  
<script>
import AgoraRTC from "agora-rtc-sdk-ng";
import axios from "axios";

export default {
    name: "AgoraLiveAudience",
    data() {
        return {
            // Agora配置
            config: {
                channel: "room_3",
                // https://live-stock.live
                tokenServer: "/v1/live_stream/getAudienceToken",
            },
            // 状态管理
            client: null,
            remoteUsers: {},
            statusMessage: "",
            tokenData: null,
            // 控件状态
            isFullscreen: false,
            isMuted: false,
            volume: 50,
            currentAudioTrack: null,
            eq: null,
            yl: true,
            isChajianVisible: true // 初始状态可见
        };
    },
    mounted() {
        // this.initAndJoin();
        // document.addEventListener('fullscreenchange', this.handleFullscreenChange);
        // this.eq = this.isIOS()

        // if (this.eq) {
        //     this.yl = false
        // } else {
        //     this.yl = true

        //     // 监听container点击
        //     this.$refs.container?.addEventListener('click', this.handleContainerClick);
        //     // 监听全屏状态变化
        //     document.addEventListener('fullscreenchange', () => {
        //         this.isFullscreen = !!document.fullscreenElement;
        //     });
        // }
    },
    beforeDestroy() {
        this.leaveChannel();
        document.removeEventListener('fullscreenchange', this.handleFullscreenChange);

        // if (!this.eq) {
        //     this.$refs.container?.removeEventListener('click', this.handleContainerClick);
        //     document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
        // }

    },
    methods: {
        isIOS() {
            return /iPad|iPhone|iPod/.test(navigator.userAgent);
        },
        // 获取Token
        async fetchToken() {
            try {
                const response = await axios.get(this.config.tokenServer, {
                    params: { room_name: this.config.channel }
                });

                if (response.data.code !== 200) {
                    throw new Error(response.data.msg || "Token error");
                }

                this.tokenData = response.data.data;
                return response.data.data;
            } catch (error) {
                console.error("Fetch token failed:", error);
                this.statusMessage = "Token error";
                throw error;
            }
        },

        // 初始化并加入频道
        async initAndJoin() {
            try {
                this.statusMessage = "get Token...";
                await this.fetchToken();

                this.client = AgoraRTC.createClient({ mode: "live", codec: "vp8" });
                if (this.client.setClientRole) {
                    await this.client.setClientRole("audience");
                }

                this.setupEventListeners();
                this.statusMessage = "Joining the channel...";

                await this.client.join(
                    this.tokenData.app_id,
                    this.tokenData.channel_name,
                    this.tokenData.token,
                    Number(this.tokenData.uid)
                );

                this.statusMessage = "Joined the channel successfully";
            } catch (error) {
                console.error("加入频道失败:", error);
                this.statusMessage = `Failed to join the channel: ${error.message}`;
            }
        },

        // 设置事件监听
        setupEventListeners() {
            this.client.on("user-published", this.handleUserPublished);
            this.client.on("user-unpublished", this.handleUserUnpublished);
            this.client.on("user-left", this.handleUserLeft);
            this.client.on("token-privilege-will-expire", this.handleTokenWillExpire);
            this.client.on("token-privilege-did-expire", this.handleTokenDidExpire);
        },

        // 处理用户发布流
        async handleUserPublished(user, mediaType) {
            try {
                await this.client.subscribe(user, mediaType);
                console.log("已订阅用户 " + user.uid + " 的 " + mediaType + " 流");

                if (mediaType === "video") {
                    this.$set(this.remoteUsers, user.uid, user);
                    this.$nextTick(() => {
                        const videoContainer = document.createElement("div");
                        videoContainer.id = `player-${user.uid}`;
                        videoContainer.style.width = '100%';
                        videoContainer.style.height = '100%';

                        videoContainer.className = "remote-video";
                        this.$refs.remoteContainer.appendChild(videoContainer);
                        user.videoTrack.play(videoContainer);
                    });
                }

                if (mediaType === "audio") {
                    user.audioTrack.play();
                    this.currentAudioTrack = user.audioTrack;
                    user.audioTrack.setVolume(this.volume);
                }
            } catch (err) {
                console.error("订阅流错误：", err);
            }
        },

        // 处理用户取消发布
        handleUserUnpublished(user, mediaType) {
            console.log("用户 " + user.uid + " 取消发布 " + mediaType + " 流");
            const videoContainer = document.getElementById(`player-${user.uid}`);
            if (videoContainer) videoContainer.remove();
            this.$delete(this.remoteUsers, user.uid);
        },

        // 处理用户离开
        handleUserLeft(user) {
            console.log("用户 " + user.uid + " 离开频道");
            const videoContainer = document.getElementById(`player-${user.uid}`);
            if (videoContainer) videoContainer.remove();
            this.$delete(this.remoteUsers, user.uid);
            if (this.currentAudioTrack && this.currentAudioTrack._id === user.audioTrack?._id) {
                this.currentAudioTrack = null;
            }
        },

        // 离开频道
        async leaveChannel() {
            try {
                if (this.client) await this.client.leave();
                this.remoteUsers = {};
                this.statusMessage = "Left the channel";
                if (this.$refs.remoteContainer) {
                    this.$refs.remoteContainer.innerHTML = "";
                }
                this.currentAudioTrack = null;
            } catch (error) {
                console.error("Leave channel failed:", error);
            }
        },

        // Token即将过期
        async handleTokenWillExpire() {
            try {
                const newToken = await this.fetchToken();
                await this.client.renewToken(newToken);
                console.log("Token续签成功");
            } catch (error) {
                console.error("Token续签失败:", error);
            }
        },

        // Token已过期
        async handleTokenDidExpire() {
            try {
                await this.leaveChannel();
                await this.initAndJoin();
            } catch (error) {
                console.error("重新加入失败:", error);
            }
        },

        // 全屏切换
        toggleFullscreen() {
            if (this.eq) {
                const videoElement = document.querySelector('video');
                console.log(videoElement, 'videoElement');
                if (videoElement) {
                    videoElement.webkitEnterFullscreen?.();
                    this.isFullscreen = true;
                }
            } else {
                if (!this.isFullscreen) {
                    this.$refs.container.requestFullscreen?.().then(() => {
                        // 进入全屏2秒后自动隐藏
                        setTimeout(() => {
                            if (this.$refs.chajian) {
                                this.$refs.chajian.style.opacity = '0';
                                this.isChajianVisible = false; // 同步状态
                            }
                        }, 2000);
                    });
                    this.isFullscreen = true;
                } else {
                    this.isFullscreen = false;
                    document.exitFullscreen?.();
                    console.log(this.$refs.chajian, 'this.$refs.chajian');
                    this.$refs.chajian.style.opacity = '';
                    // this.$refs.container.removeEventListener('click', this.handleContainerClick);

                }
            }
        },
        handleContainerClick(e) {
            console.log(e.target !== this.$refs.container, 'e.target');
            // 仅在全屏状态时响应点击
            // if (e.target !== this.$refs.remoteContainer) return;
            if (this.isFullscreen && this.$refs.chajian) {
                this.isChajianVisible = !this.isChajianVisible;
                this.$refs.chajian.style.opacity = this.isChajianVisible ? '1' : '0';
            }
        },
        // 检测全屏状态变化
        handleFullscreenChange() {
            this.isFullscreen = !!document.fullscreenElement;
        },

        // 静音切换
        toggleMute() {
            this.isMuted = !this.isMuted;
            if (this.currentAudioTrack) {
                this.currentAudioTrack.setVolume(this.isMuted ? 0 : this.volume);
            }
        }
    },
    watch: {
        // 音量变化处理
        volume(newVal) {
            if (this.currentAudioTrack) {
                this.currentAudioTrack.setVolume(newVal);
                this.isMuted = newVal === 0;
            }
        }
    }
};
</script>
  
<style scoped>
#zzzaaa {
    width: 100%;
    height: 100%;
}

.mmmbbb {
    width: 100%;
    height: 100%;
    position: absolute;
    background-color: #000;
}

.agora-container {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: #000;
}

.agora-container:hover .controls-bar {
    opacity: 1;
}

#remote-container {
    width: 100%;
    height: 100%;
}

.remote-video {
    width: 100%;
    height: 100%;
}

/* 控制栏样式 */
.controls-bar {
    opacity: 0;
    transition: opacity 0.4s ease-in-out;
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    padding: 8px 15px;
    background: rgba(0, 0, 0, 0.7);
    border-radius: 20px;
    gap: 12px;
    z-index: 10;
}

.control-btn {
    background: rgba(255, 255, 255, 0.1);
    border: none;
    color: white;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    min-width: 80px;
    transition: background 0.2s;
}

.control-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.volume-slider {
    width: 100px;
    height: 6px;
    cursor: pointer;
}

.volume-text {
    color: white;
    font-size: 14px;
    min-width: 40px;
    text-align: center;
}

@media screen and (max-width: 499px) {
    .controls-bar {
        padding: 8px 5px;
        width: 100%;
        border-radius: 0;
        justify-content: space-between;

    }

    .control-btn {
        font-size: 12px;

    }
}

.Title_module_header__296cb5dd {
    display: none !important
    ;
}
</style>